<template>
  <div class="page-mobile-wallet">
    <white-header
      :isShowTopNav="true"
      :isShowBack="true"
      :isShowRight="true"
      title="账号充值"
    ></white-header>
    <div class="balance">
      <div class="balance-header">
        <img src="/img/mobile/money.png" alt="" />
        <div class="balance-title">账户余额</div>
        <div class="balance-center">
          <div class="money">
            <no-ssr>
              <animate-number
                :from="num_start"
                :to="user_info.balance || 0"
                ref="number"
                duration="1000"
                easing="easeOutQuad"
                :formatter="formatter"
              ></animate-number>
            </no-ssr>
          </div>
          <div class="yen">元</div>
        </div>
      </div>
    </div>
    <div class="recharge">
      <div class="recharge-title">充值</div>
      <div class="recharge-box">
        <div
          :class="['box-item', item.is_select && !is_allow ? 'active' : '']"
          v-for="(item, index) in recharge_num_list"
          :key="index"
          @click="handleChangeNum(item, index)"
        >
          <div class="m-t">{{ item.origin_price }}元</div>
          <div class="m-m">支付{{ item.price }}元</div>
        </div>
      </div>
      <div class="money-input">
        自定义金额（元）
        <input
          type="number"
          class="money-number"
          placeholder="请输入充值金额（元）"
          v-model="recharge_num"
          @input="handleInput"
        />
      </div>
    </div>
    <div class="pay-content">
      <div class="pay-title">支付方式</div>
      <div class="pay-box">
        <van-radio-group v-model="pay_radio">
          <div class="wechat" @click="handleChangeType('wechatpay')">
            <div class="pay-left">
              <img src="/img/mobile/member_payment_wechat.png" alt="" />
              <span class="pay-name">微信支付</span>
            </div>
            <div class="pay-right">
              <van-radio name="wechatpay"></van-radio>
            </div>
          </div>
          <div
            class="alipay"
            @click="handleChangeType('alipay')"
            v-if="!is_in_wechat"
          >
            <div class="pay-left">
              <img src="/img/mobile/member_payment_alipay.png" alt="" />
              <span class="pay-name">支付宝支付</span>
            </div>
            <div class="pay-right"><van-radio name="alipay"></van-radio></div>
          </div>
        </van-radio-group>
      </div>
    </div>
    <div class="pay-submit" @click="handlePay">确认支付</div>
  </div>
</template>

<script>
import {
  buildOrder,
  buildH5Order,
  buildAliOrder,
  checkOrderNum,
  cardActivate,
  buildAliAppOrder,
  buildWeChatAppOrder
} from "~/api/account/wallet";
import { getWaterList } from "~/api/order";
import { wexinPay, wxJspay } from "~/utils/pay";
import { socketUrl } from "~/config/conf";
import WhiteHeader from "~/components/mobile/WhiteHeader.vue";
import { mapState, mapActions, mapMutations } from "vuex";
// import VueAnimateNumber from "vue-animate-number";
// if (process.client) {
//   // console.log(window);
//   const VueAnimateNumber = require("vue-animate-number").install(this);
//   console.log("VueAnimateNumber:", VueAnimateNumber);
// }
export default {
  // components: process.client
  //   ? {
  //       AnimateNumber: VueAnimateNumber
  //     }
  //   : {},
  props: ["setDisabled", "refreshFun", "setLoading"],
  components: {
    WhiteHeader
  },
  data() {
    return {
      // 临时变量
      pay_radio: "wechatpay",

      active: "recharge",
      recharge_num: "", //手动输入的金额
      card_account: "", //激活码
      websock: null, //websocket
      num_start: 0, //数字动画起始数
      recharge_num_list: [
        {
          price: 30,
          origin_price: 30,
          is_select: true
        },
        {
          price: 50,
          origin_price: 50,
          is_select: false
        },
        {
          price: 100,
          origin_price: 100,
          is_select: false
        },
        {
          price: 150,
          origin_price: 150,
          is_select: false
        },
        {
          price: 200,
          origin_price: 200,
          is_select: false
        },
        {
          price: 300,
          origin_price: 300,
          is_select: false
        }
      ],
      // recharge_type_list: [
      //   {
      //     type: "wechatpay",
      //     name: this.$t("locale.mobile.wallet.t21"),
      //     is_select: true
      //   },
      //   {
      //     type: "alipay",
      //     name: this.$t("locale.mobile.wallet.t22"),
      //     is_select: false
      //   }
      // ],
      water_list: [], //资金流水
      timer: null, //节流计时器
      socketFailedCount: 0 //socket重连计数器
    };
  },
  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      token(state) {
        return state.token;
      },
      is_ios(state) {
        return state.is_ios;
      },
      is_in_wechat(state) {
        return state.is_in_wechat;
      },
      is_in_minigram(state) {
        return state.is_in_minigram;
      },
      is_wechat_ios_limit(state) {
        return state.is_wechat_ios_limit;
      }
    }),
    is_show_price() {
      if (this.is_wechat_ios_limit) {
        return this.is_ios && this.is_in_wechat;
      } else {
        return false;
      }
    },
    is_allow() {
      if (!this.recharge_num) {
        return false;
      } else {
        return true;
      }
    },
    active_query() {
      return this.$route.query.active;
    },
    num() {
      return this.$route.query.num;
    },
    redirect_url() {
      return this.$route.query.rdurl;
    },
    //支付宝支付后返回的订单信息
    orderInfo() {
      return this.$route.query;
    }
  },
  watch: {
    user_info(new_val, old_val) {
      this.$refs.number.reset();
      this.$refs.number.updateNumber({
        x: new_val.balance
      });
    }
  },
  destroyed() {
    this.timer = null;
    this.socketFailedCount = 0;
    this.toggleScroll(false);
    this.closeConnection();
    this.setDisabled(true);
  },
  deactivated() {
    this.timer = null;
    this.socketFailedCount = 0;
    this.toggleScroll(false);
    this.closeConnection();
    this.setDisabled(true);
  },
  activated() {
    if (process.client) {
      if (!this.token && Object.keys(this.user_info).length == 0) {
        this.$router.replace("/m/login");
      }
    }
    this.toggleScroll(true);
    this.initWebSocket();
    this.setDisabled(false);
    this.refreshFun(() => {
      this.initUser();
      this.getWaterListFun();
      this.setLoading(false);
    });
  },
  methods: {
    ...mapActions(["initBuyCourseRecord", "initUser"]),
    ...mapMutations([
      "SET_IS_LOADING",
      "UPDATE_USERINFO",
      "UPDATE_BUYRECORD_LIST"
    ]),
    formatter(num) {
      return num && num.toFixed(2);
    },
    handleChangeNum(item, index) {
      this.recharge_num_list = this.recharge_num_list.map((i, x) => {
        if (index == x) {
          // if (item.is_select) {
          //   return {
          //     ...i,
          //     is_select: false
          //   };
          // }
          return {
            ...i,
            is_select: true
          };
        } else {
          return {
            ...i,
            is_select: false
          };
        }
      });
    },
    handleChangeType(type) {
      this.pay_radio = type;
    },
    handleTapChange(name, title) {
      this.$router.replace({
        path: "",
        query: {
          active: name
        }
      });
    },
    async handlePay() {
      if (process.client) {
        //获取支付类型
        let pay_type = this.pay_radio;
        let params = {
          userid: this.user_info.id
        };
        //手动输入的金额
        const { recharge_num } = this;
        //卡片的金额
        let recharge_card_num = this.recharge_num_list.filter(
          i => i.is_select
        )[0].price;
        params = {
          ...params,
          amount: Number(recharge_card_num) * 100
        };
        //手动输入的金额和卡片的金额同时存在，充值金额为手动输入的金额
        if (recharge_num) {
          params = {
            ...params,
            amount: Number(recharge_num) * 100
          };
        }
        if (pay_type == "wechatpay") {
          
          console.log("=====================微信支付=====================");
          params = {
            ...params,
            body:
              this.$t("locale.mobile.wallet.t23") +
              params.amount / 100 +
              this.$t("locale.mobile.wallet.t18")
          };
          //微信内置浏览器内
          if (this.is_in_wechat) {
            if (this.is_in_minigram) {
              console.log(
                "=====================微信小程序支付====================="
              );
              wx.miniProgram.navigateTo({
                url: `/pages/pay/pay?userid=${params.userid}&amount=${params.amount}&body=${params.body}`,
                success: function() {
                  console.log("成功跳转小程序");
                },
                fail: function() {
                  console.log("跳转小程序失败");
                },
                complete: function() {
                  console.log("完成");
                }
              });
            } else {
              console.log("=================判断是否绑定微信=================");
              if(!(this.user_info.wechatOpenid && this.user_info.wechatOpenid.replace(/(\s*$)/g, '')) && this.is_in_wechat){
                this.$dialog.confirm({
                  title: '提示',
                  message: '您尚未绑定微信，请先绑定微信再进行支付哟！',
                  confirmButtonText:"去绑定"
                })
                  .then(() => {
                    this.$router.push('/m/setting')
                  })
                  .catch(() => {
                  });
                return;
              }
              let result = await buildOrder(params);
              if (result && result.data && result.data.code == 200) {
                const { data } = result.data;
                console.log(result);

                console.log(
                  "=====================微信JS支付====================="
                );
                wxJspay(
                  data,
                  res => {
                    console.log("微信JS支付结果：", res);
                  },
                  err => {
                    console.log(err);
                  }
                );
              } else {
                this.$toast(
                  this.$t("locale.mobile.wallet.t24") + result &&
                    result.data &&
                    result.data.msg
                );
              }
            }
          } else {
            //微信内置浏览器外（H5pay）
            if (window.hasOwnProperty("flutter_inappwebview")) {
              console.log(
                "=====================微信App支付====================="
              );
              let result = await buildWeChatAppOrder(params);
              if (result && result.data && result.data.code == 200) {
                const {
                  appid,
                  partnerid,
                  noncestr,
                  timestamp,
                  signType,
                  sign,
                  prepayid
                } = result.data.data;
                // let __ = result.data.data.package.split("=");
                // let prepayId = __ ? __[__.length - 1] : "";

                /**
                window.Pay.postMessage(
                  JSON.stringify({
                    type: "wxpay",
                    data: {
                      appId: appid,
                      partnerId: partnerid,
                      prepayId: prepayid,
                      packageValue: result.data.data.package,
                      nonceStr: noncestr,
                      timeStamp: timestamp,
                      // signType,
                      sign: sign,
                      amount: params.amount / 100
                    }
                  })
                );
                **/
                let arg = JSON.stringify({
                  type: "wxpay",
                  data: {
                    appId: appid,
                    partnerId: partnerid,
                    prepayId: prepayid,
                    packageValue: result.data.data.package,
                    nonceStr: noncestr,
                    timeStamp: timestamp,
                    // signType,
                    sign: sign,
                    amount: params.amount / 100
                  }
                });
                window.flutter_inappwebview
                  .callHandler("Pay", arg)
                  .then(res => {
                    console.log("微信支付成功！");
                    console.log(res);
                  });
              } else {
                this.$toast(
                  this.$t("locale.mobile.wallet.t24") + result.data
                    ? result.data.msg
                    : null
                );
              }
            } else {
              console.log(
                "=====================微信H5支付====================="
              );
              let result = await buildH5Order(params);
              if (result && result.data && result.data.code == 200) {
                const { data } = result.data;
                console.log(result);
                window.location.href = `${
                  data.mweb_url
                }&redirect_url=${encodeURIComponent(window.location.href)}`;
                // wexinPay(
                //   data,
                //   res => {
                //     console.log("微信H5支付结果：", res);
                //   },
                //   err => {
                //     console.log(err);
                //   }
                // );
              } else {
                this.$toast(
                  this.$t("locale.mobile.wallet.t24") + result.data
                    ? result.data.msg
                    : null
                );
              }
            }
          }
        } else if (pay_type == "alipay") {
          if (window.hasOwnProperty("flutter_inappwebview")) {
            console.log(
              "=====================支付宝App支付====================="
            );
            params = {
              ...params,
              amount: params.amount / 100
            };
            params = {
              ...params,
              orderNo: this.user_info.id + new Date().getTime(),
              body:
                this.$t("locale.mobile.wallet.t23") +
                params.amount +
                this.$t("locale.mobile.wallet.t18")
            };
            let result = await buildAliAppOrder(params);
            console.log(result);
            if (result && result.data && result.data.code == 200) {
              /**window.Pay.postMessage(
                JSON.stringify({
                  type: "alipay",
                  data: result.data.data
                })
              );
              **/
              let arg = JSON.stringify({
                type: "alipay",
                data: result.data.data
              });
              window.flutter_inappwebview.callHandler("Pay", arg).then(res => {
                console.log("支付宝支付成功！");
                console.log(res);
              });
            } else {
              this.$toast(
                this.$t("locale.mobile.wallet.t24") + result.data
                  ? result.data.msg
                  : null
              );
            }
          } else {
            console.log("=====================支付宝支付=====================");
            //支付宝充值金额不用除100
            params = {
              ...params,
              amount: params.amount / 100
            };
            params = {
              ...params,
              orderNo: this.user_info.id + new Date().getTime(),
              body:
                this.$t("locale.mobile.wallet.t23") +
                params.amount +
                this.$t("locale.mobile.wallet.t18")
            };
            let result = await buildAliOrder(params);
            console.log(result);
            if (result && result.data && result.data.code == 200) {
              window.location.href = result.data.data;
            } else {
              this.$toast(
                this.$t("locale.mobile.wallet.t24") + result.data
                  ? result.data.msg
                  : null
              );
            }
          }
        }
      }
    },
    getNum(num, n) {
      if (num === 0) {
        return "0.00";
      } else {
        let copy_num = Number(num) / 100;
        let str = String(copy_num);
        let index = str.indexOf(".");
        let str1 = str.substring(0, index + n + 1);
        str1 = parseFloat(str1);
        console.log(str1);
        return str1;
      }
    },
    handleInput(e) {
      console.log("E:", e);
      let result = String(e).split(".");
      console.log("result:", result);
      console.log(result[result.length - 1].length <= 2);
      if (result.length > 1) {
        if (result[result.length - 1].length <= 2) {
          this.recharge_num = e;
        } else {
          this.recharge_num = parseFloat(
            result[0] + "." + result[result.length - 1].substring(0, 2)
          );
        }
      }
    },
    initWebSocket() {
      if (process.client) {
        if ("WebSocket" in window) {
          //初始化weosocket
          const wsuri = socketUrl + "pay/" + this.user_info.id;
          this.websock = new WebSocket(wsuri);
          this.websock.onmessage = this.websocketonmessage;
          this.websock.onopen = this.websocketonopen;
          this.websock.onerror = this.websocketonerror;
          this.websock.onclose = this.websocketclose;

          window.addEventListener("beforeunload", this.closeConnection, false);
        } else {
          this.$toast(this.$t("locale.mobile.wallet.t25"));
        }
      }
    },
    websocketonopen() {
      //连接建立之后执行send方法发送数据
      console.log("成功建立socket连接");
      clearTimeout(this.timer);
      this.timer = null;
      this.socketFailedCount = 0;
    },
    websocketonerror() {
      //连接建立失败重连
      console.log("socket连接失败！");
      this.retryConnectSocket();
    },
    websocketonmessage(e) {
      //数据接收
      console.log("收到socket:", e);
      console.log(JSON.parse(e.data));
      // debugger;
      try {
        const result = JSON.parse(e.data);
        let message = JSON.parse(result.message);
        if (message.code == 200) {
          let recharge = message.data.cashFee || 0;
          // //手动输入的金额
          // const { recharge_num } = this;
          // //卡片的金额
          // let recharge_card_num = this.recharge_num_list.filter(
          //   i => i.is_select
          // );
          // if (recharge_card_num.length > 0) {
          //   recharge = recharge_card_num[0].price;
          // }
          // if (recharge_num) {
          //   recharge = recharge_num;
          // }
          console.log("增加余额:", recharge);
          this.num_start = this.user_info.balance;
          this.UPDATE_USERINFO({
            balance: Number(this.user_info.balance) + Number(recharge)
          });
          this.$toast(this.$t("locale.mobile.wallet.t26"));
          // if (this.redirect_url) {
          //   this.$router.replace(this.redirect_url);
          // }
        } else {
          this.$toast(this.$t("locale.mobile.wallet.t27"));
        }
      } catch (e) {
        console.log(e);
      }
    },
    websocketsend(Data) {
      //数据发送
      this.websock.send(Data);
    },
    websocketclose(e) {
      //关闭
      console.log("断开连接", e);
      this.retryConnectSocket();
    },
    closeConnection() {
      return new Promise((res, rej) => {
        try {
          window.removeEventListener("beforeunload", this.closeConnection);
          this.websock && this.websock.close();

          if(this.timer){
            clearTimeout(this.timer);
            this.timer = null;
            this.socketFailedCount = 0;
          }
        } catch (e) {
          console.log("关闭socket错误：", e);
        }
        res();
      }).then();
    },
    async getWaterListFun() {
      this.SET_IS_LOADING(true);
      let result = await getWaterList({
        sort: "id desc"
      });
      console.log("result:", result);
      if (result && result.data && result.data.code == 200) {
        this.water_list = result.data.data.rows;
        this.SET_IS_LOADING(false);
      } else {
        this.SET_IS_LOADING(false);
        this.$toast(this.$t("locale.mobile.wallet.t28"));
      }
    },
    async checkOrder() {
      console.log("this.orderInfo:", this.orderInfo);
      this.SET_IS_LOADING(true);
      let params = {
        outTradeNo: this.orderInfo.out_trade_no
      };
      let result = await checkOrderNum(params);
      if (result && result.data && result.data.code == 200) {
        this.num_start = this.user_info.balance;
        let new_balance =
          Number(this.user_info.balance) + Number(this.orderInfo.total_amount);
        console.log("new_balance:", new_balance);
        this.UPDATE_USERINFO({
          balance: new_balance
        });
        this.$toast(this.$t("locale.mobile.wallet.t26"));
        this.getWaterListFun();
        this.SET_IS_LOADING(false);
      } else {
        this.SET_IS_LOADING(false);
        this.$toast(this.$t("locale.mobile.wallet.t27"));
      }
    },
    async activeCard() {
      if (!this.card_account) {
        return this.$toast(this.$t("locale.mobile.wallet.t29"));
      }
      this.SET_IS_LOADING(true);
      let params = {
        userId: this.user_info.id,
        code: this.card_account
      };
      let result = await cardActivate(params);
      console.log("激活码：", result);
      if (result && result.data && result.data.code == 200) {
        this.UPDATE_BUYRECORD_LIST(result.data.data);
        this.SET_IS_LOADING(false);
        this.$toast(this.$t("locale.mobile.wallet.t30"));
        this.card_account = "";
        this.initBuyCourseRecord();
      } else {
        this.SET_IS_LOADING(false);
        this.$toast(
          this.$t("locale.mobile.wallet.t31"),
          result && result.data && result.data.msg
        );
      }
    },
    trimDate(date) {
      if (date) {
        let _date = new Date(date);
        return `${_date.getFullYear()}.${_date.getMonth() +
          1}.${_date.getDate()}  ${_date.getHours()}:${_date.getMinutes()}:${_date.getSeconds()}`;
      } else {
        return this.$t("locale.mobile.wallet.unknow");
      }
    },
    closeScroll() {
      this.setDisabled(false);
    },
    openScroll() {
      this.setDisabled(true);
    },
    toggleScroll(type) {
      if (type) {
        // document
        //   .querySelector(".van-tabs__content")
        //   .addEventListener("touchmove", this.openScroll);
        // document
        //   .querySelector(".van-tabs__content")
        //   .addEventListener("touchend", this.closeScroll);
      } else {
        // document.removeEventListener("touchmove", this.openScroll);
        // document.removeEventListener("touchend", this.closeScroll);
      }
    },
    retryConnectSocket() {
      this.debounce(async () => {
        if (this.socketFailedCount < 10) {
          this.socketFailedCount = this.socketFailedCount + 1;
          await this.closeConnection();
          this.initWebSocket();
        } else {
          console.info("websocket fail to connection , please retry later!");
          this.timer = null;
        }
      }, 3000);
    },
    debounce(fn, wait) {
      return !(() => {
        if (this.timer !== null) {
          clearTimeout(this.timer);
        }
        this.timer = setTimeout(fn, wait);
      })();
    }
  },
  created() {
    if (process.client) {
      if (!this.token && Object.keys(this.user_info).length == 0) {
        return this.$router.replace("/m/login");
      }
      if (
        ["recharge", "recharge-card", "financial-details"].includes(
          this.active_query
        )
      ) {
        this.active = this.active_query;
      } else {
        this.active = "recharge";
      }
      if (this.num) {
        this.recharge_num = this.num;
      }
      this.getWaterListFun();
      if (this.orderInfo.out_trade_no) {
        this.checkOrder();
      }
      this.initWebSocket();
      this.$nextTick(() => {
        this.toggleScroll(true);
      });
      console.log(window);
      console.log(window.flutter_inappwebview);
    }
    this.setDisabled(false);
    this.refreshFun(() => {
      this.initUser();
      this.getWaterListFun();
      this.setLoading(false);
    });
  },
  mounted() {}
};
</script>

<style lang="scss" scoped>
.page-mobile-wallet {
  width: 100vw;
  min-height: 100vh;
  background-color: #f7f7fa;
  margin-bottom: 1rem;
  .balance {
    padding: 0.3rem 0;
    .balance-header {
      width: 6.624rem;
      height: 2.496rem;
      background-color: var(--theme-color);
      margin: 0 auto;
      border-radius: 0.192rem;
      padding: 0.26rem;
      position: relative;
      .balance-title {
        color: #ffffff;
        font-size: 0.3072rem;
        font-weight: bold;
      }
      .balance-center {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 0.5rem;
        color: #ffffff;
        .money {
          font-size: 0.6144rem;
        }
        .yen {
          font-weight: bold;
          font-size: 0.34559rem;
        }
      }
      img {
        width: 2.4576rem;
        height: 2.0832rem;
        position: absolute;
        right: 0;
        bottom: 0;
      }
    }
  }
  .recharge {
    padding: 0.288rem;
    background: #ffffff;
    .recharge-title {
      font-size: 0.34559rem;
      font-weight: bold;
      color: #313233;
      margin-bottom: 0.3rem;
    }
    .recharge-box {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      .box-item {
        width: 2.016rem;
        height: 1.248rem;
        background-color: #f2f5f7;
        border-radius: 0.1rem;
        margin-bottom: 0.3rem;
        color: #949799;
        padding: 0.3rem 0;
        .m-t {
          text-align: center;
          font-size: 0.34559rem;
        }
        .m-m {
          text-align: center;
          font-size: 0.2496rem;
        }
      }
      .box-item.active {
        background-color: var(--theme-color);
        color: #ffffff;
      }
    }
    .money-input {
      color: #313233;
      font-size: 0.2688rem;
      .money-number {
        width: 4.35rem;
        height: 0.576rem;
        line-height: 0.576rem;
        padding: 0 0.2rem;
        font-size: 0.2688rem;
        border: 0.01rem solid #dfe2e5;
      }
    }
  }
  .pay-content {
    padding: 0.288rem;
    background: #ffffff;
    margin-top: 0.3rem;
    .pay-title {
      font-size: 0.34559rem;
      font-weight: bold;
      color: #313233;
      margin-bottom: 0.3rem;
    }
    .pay-box {
      .wechat {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 0.2rem;
        margin-bottom: 0.4rem;
        .pay-left {
          display: flex;
          align-items: center;
          img {
            width: 0.4224rem;
            height: 0.4224rem;
            display: block;
          }
          .pay-name {
            font-size: 0.26rem;
            margin: 0 0.1rem;
          }
        }
        .pay-right {
        }
      }
      .alipay {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 0.2rem;
        margin-bottom: 0.2rem;
        .pay-left {
          display: flex;
          align-items: center;
          img {
            width: 0.4224rem;
            height: 0.4224rem;
            display: block;
          }
          .pay-name {
            font-size: 0.26rem;
            margin: 0 0.1rem;
          }
        }
        .pay-right {
        }
      }
    }
  }
  .pay-submit {
    width: 100%;
    height: 1rem;
    line-height: 1rem;
    font-size: 0.3rem;
    font-weight: bold;
    text-align: center;
    position: fixed;
    left: 0;
    bottom: 0;
    background: var(--theme-color);
    color: #ffffff;
  }
}
</style>
<style lang="scss">
.page-mobile-wallet {
}
</style>
